package admin

import (
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	"yixiang.co/yshop/common/jwt"
	"yixiang.co/yshop/controllers"
	"yixiang.co/yshop/models"
	"yixiang.co/yshop/models/vo"
)

// 素材api
type MaterialController struct {
	controllers.BaseController
}

func (c *MaterialController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// @Title 素材列表
// @Description 岗位列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *MaterialController) GetAll() {
	groupId, _ := c.GetInt64("groupId", -1)
	logs.Info(groupId)
	total, list := models.GetAllMaterial(c.GetParams(), groupId)
	c.Ok(vo.ResultList{Content: list, TotalElements: total})
}

// @Title 素材添加
// @Description 素材添加
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *MaterialController) Post() {
	var model models.SysMaterial
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	c.Valid(&model)
	uid, _ := jwt.GetAdminUserId(c.Ctx.Input)
	model.CreateId = uid
	_, e := models.AddMaterial(&model)
	if e != nil {
		c.Fail(e.Error(), 5002)
	}
	c.Ok("操作成功")
}

// @Title 素材修改
// @Description 素材修改
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *MaterialController) Put() {
	var model models.SysMaterial
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	c.Valid(&model)
	e := models.UpdateByMaterial(&model)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// @Title 素材删除
// @Description 素材删除
// @Success 200 {object} controllers.Result
// @router /:id [delete]
func (c *MaterialController) Delete() {
	var ids []int64
	id, _ := c.GetInt64(":id", 0)
	ids = append(ids, id)
	logs.Info(ids)
	e := models.DelByMaterial(ids)
	if e != nil {
		c.Fail(e.Error(), 5005)
	}
	c.Ok("操作成功")
}

// @Title 上传图像
// @Description 上传图像
// @Success 200 {object} controllers.Result
// @router /upload [post]
func (c *MaterialController) Upload() {
	logs.Info("======file start======")
	f, h, err := c.GetFile("file")
	if err != nil {
		logs.Error(err)
	}
	defer f.Close()
	var path = "static/upload/" + h.Filename
	e := c.SaveToFile("file", path) // 保存位置在 static/upload, 没有文件夹要先创建
	logs.Error(e)
	if e != nil {
		c.Fail(e.Error(), 5009)
	}
	apiUrl, _ := beego.AppConfig.String("api_url")
	imgUrl := apiUrl + "/" + path

	c.Ok(imgUrl)
}
